<!--
 * @Author: wangyongcun@persagy.com
 * @Date: 2025-03-06 21:47:10
 * @LastEditTime: 2025-03-23 10:25:32
 * @FilePath: \vite-admin\src\components\appSetting\ThemeSchema.vue
 * @Description:
 *
-->
<template>
  <CommonTipIcon
    :icon="iconComponent"
    :showTooltip="showTooltip"
    :tooltipContent="tooltipContent"
    @click="handleClick"
  />
</template>

<script setup lang="ts">
interface Props {
  // 模式:switch-单选切换,tab-多选切换
  mode?: "switch" | "tab";
  // 是否显示tooltip
  showTooltip?: boolean;
  // tooltip的位置
  tooltipPlacement?: string;
}

const props = withDefaults(defineProps<Props>(), {
  mode: "switch",
  showTooltip: true,
  tooltipPlacement: "bottom",
});

const appSetting = useAppSetting();
const theme = computed(() => appSetting.theme);
const changeTheme = appSetting.changeTheme;

const themeMap: Record<Theme, { icon: string; tooltip: string; next: Theme }> =
  {
    light: {
      icon: "material-symbols:sunny",
      tooltip: "亮色模式",
      next: "dark",
    },
    dark: {
      icon: "material-symbols:nightlight-rounded",
      tooltip: "暗色模式",
      next: "light",
    },
    auto: {
      icon: "material-symbols:hdr-auto",
      tooltip: "跟随系统",
      next: "light",
    },
  };

const iconComponent = computed(() => themeMap[theme.value].icon);
const tooltipContent = computed(() =>
  props.showTooltip ? themeMap[theme.value].tooltip : ""
);

// 主题切换处理
const handleClick = () => {
  const newTheme = themeMap[theme.value].next;
  changeTheme(newTheme);
};

// 更新主题类名
const updateThemeClass = (value: Theme) => {
  const html = document.documentElement;
  if (value === "dark" || (value === "auto" && usePreferredDark().value)) {
    html.classList.add("dark");
  } else {
    html.classList.remove("dark");
  }
};

// 监听主题变化
watch(
  theme,
  (value) => {
    updateThemeClass(value);
  },
  {
    immediate: true,
  }
);
</script>

<style scoped></style>
